package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.SystemMessage;
import cn.wolfcode.trip.base.domain.UserMessage;
import cn.wolfcode.trip.base.mapper.SystemMessageMapper;
import cn.wolfcode.trip.base.mapper.UserMessageMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.query.SystemMessageQueryObject;
import cn.wolfcode.trip.base.service.ISystemMessageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SystemMessageImpl implements ISystemMessageService {
    @Autowired
    private SystemMessageMapper systemMessageMapper;
    @Autowired
    private UserMessageMapper userMessageMapper;


    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List list = systemMessageMapper.selectForList(qo);
        return new PageInfo(list);
    }

    @Override
    public void setRead(Long sid, Long userId, Integer type) {
        if(type==1){
            SystemMessage systemMessage = systemMessageMapper.selectByPrimaryKey(sid);
            UserMessage um = new UserMessage();
            um.setContent(systemMessage.getContent());
            um.setMsgId(systemMessage.getId());
            um.setSendTime(systemMessage.getSendTime());
            um.setState(true);
            um.setUserId(userId);
            userMessageMapper.insert(um);
        }else if(type==2){
            SystemMessageQueryObject qo = new SystemMessageQueryObject();
            qo.setUserId(userId);
            qo.setPageSize(0);
            /*该用户所有消息,包括已读和未读*/
            List<SystemMessage> list = systemMessageMapper.selectForList(qo);
            for (SystemMessage message : list) {
                /*如果未收藏*/
                if (!message.isState()) {
                setRead(message.getId(),userId,1);
                }
            }
        }

    }
}
